<script setup lang="ts">
import { Button, Dropdown, Input, Menu, Pagination, message } from 'ant-design-vue';
import { debounce } from 'lodash';
import { onMounted, ref, watch } from 'vue';
import { getCategoryApi, getDatasetMetadataApi } from "@/api/data/dataset";
import { DownOutlined } from '@ant-design/icons-vue';
import { useDatasetStore } from '@/stores/useDatasetsStore';
import type { Payload } from '@/types/data/dataset';
const PAGE_SIZE_DEFAULT = 12;

const datasetStore = useDatasetStore();

// 定义响应式变量
const categories = ref<string[]>(['全部']); // 初始化为包含“全部”
const selectedCategory = ref<string>('全部');
const keywords = ref<string>('');
const page = ref<number>(1);
const sortOption = ref<string>('最热'); // 符合后端要求的默认值

const total = ref<number>(0);
const pageSize = ref<number>(PAGE_SIZE_DEFAULT);
const payload = ref<Payload>();
// 获取分类标签
const fetchCategories = async () => {
  try {
    const response = await getCategoryApi();
    // console.log('fetchCategories response:', response);
    categories.value = ['全部', ...response];
    // 如果当前选中的分类不在新获取的分类中，重置为“全部”
    if (!categories.value.includes(selectedCategory.value))
      selectedCategory.value = '全部';
  }
  catch (error: any) {
    console.error('Error fetching categories:', error);
    message.error('请求分类标签时发生错误，请稍后再试。');
  }
};

// 获取数据集
const fetchData = async () => {
  payload.value = {
    sortBy: sortOption.value,
    keywords: keywords.value || undefined,
    page: page.value,
    size: pageSize.value,
  };
  try {
    if (selectedCategory.value !== '全部')
      payload.value.tag = selectedCategory.value

    const response = await getDatasetMetadataApi(payload.value);
    // console.log('fetchData response:', response);
    if (response) {
      datasetStore.setDatasets(response.records, response.total, page.value)
      total.value = datasetStore.total;
    }
  }
  catch (error) {
    console.error('Request failed:', error);
    message.error('获取数据集数据时出现错误');
  }
}

// 处理分类点击
const handleCategoryClick = (category: string) => {
  selectedCategory.value = category;
  page.value = 1;
  fetchData();
};

// 处理搜索
const handleSearch = debounce((value: string) => {
  keywords.value = value;
  page.value = 1;
  fetchData();
}, 300);

// 处理排序更改
const handleSortChange = (info: any) => {
  if (info.key === 'download_num')
    sortOption.value = '最热';
  else if (info.key === 'views_num')
    sortOption.value = '最新';
  else
    sortOption.value = info.key.toString();

  page.value = 1;
  fetchData();
};

// 处理分页更改
const handlePageChange = (pageValue: number, pageSizeValue?: number) => {
  page.value = pageValue;
  if (pageSizeValue)
    pageSize.value = pageSizeValue;
  fetchData();
};

// 组件挂载时获取分类和数据
onMounted(async () => {
  await fetchCategories(); // 先获取分类
  fetchData();
});

// 监视依赖项变化并获取数据
watch([sortOption, page, pageSize, selectedCategory], () => {
  fetchData();
});
</script>

<template>
  <div class="search-bar">
    <Dropdown>
      <template #overlay>
        <Menu @click="handleSortChange">
          <Menu.Item key="download_num">
            最热
          </Menu.Item>
          <Menu.Item key="views_num">
            最新
          </Menu.Item>
        </Menu>
      </template>
      <Button style="border: none; background-color: transparent;">
        排序：{{ sortOption }}
        <DownOutlined />
      </Button>
    </Dropdown>
    <Input.Search
      v-model:value="keywords"
      placeholder="搜索数据集"
      style="width: 240px"
      @search="handleSearch"
    />
  </div>
  <div class="category-menu">
    <a-flex class="category-buttons" gap="small">
      <Button
        v-for="(category, index) in categories.slice(0, 10)"
        :key="index"
        :type="selectedCategory === category ? 'primary' : 'default'"

        size="middle"
        @click="handleCategoryClick(category)"
      >
        {{ category }}
      </Button>
    </a-flex>
  </div>
  <Pagination
    size="small"
    :current="page"
    :total="total"
    :page-size="pageSize"
    show-quick-jumper
    :show-total="(total: any) => `Total ${total} items`"
    style="text-align: center; font-size: 0.8rem; background-color: #f6f6f6"
    @change="handlePageChange"
  />
</template>

<style scoped lang="scss">
.category-buttons {
  overflow-x: auto;
  width:max-content;
}
.search-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0.5rem 0; // 8px 0px -> 0.5rem 0
  .ant-btn,
  .ant-select,
  .ant-input-search {
    margin-right: 1rem; // 16px -> 1rem
  }
  margin-right: 8px;

  .ant-btn:last-child,
  .ant-input-search:last-child {
    margin-right: 0; // 最后一个元素不需要右边距
  }
}

.category-menu {
  display: flex;
  align-items: center;
  margin-top: 0.325rem; // 10px -> 0.625rem
  border-color: white;
  border-radius: 0rem;
  margin-right: 8px;
  margin-bottom: 8px;
  margin-left: 8px;
}
</style>
